package com.monolithiot.camera;

import com.monolithiot.camera.service.CameraClient;
import com.monolithiot.camera.service.ProtonServer;
import com.monolithiot.camera.service.SocketServer;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;


public class CameraApplicationMain {
    public static Logger logger = Logger.getLogger("CameraApplicationMain");
    private static final int portForProton = 9990;

    public static void main(String[] args) throws InterruptedException {
        //相机IP
        String cameraIp;
        //相机端口
        int cameraPort;
        //本机IP地址
        String localIp= getLocalIp();
        System.out.println("--------------请为 Proton 提供以下连接--------------");
        System.out.println("-                                              -");
        System.out.println("-                                              -");
        System.out.println("-               " + "\u001B[34;4m" + localIp + ":" + portForProton + "\u001B[0m" + "                 -");
        System.out.println("-                                              -");
        System.out.println("-                                              -");
        System.out.println("------------------------------------------------");
        Scanner scanner = new Scanner(System.in);
        // 获取 IP 地址
        System.out.println("请输入客流相机IP，按回车键结束，格式：x.x.x.x");
        cameraIp = scanner.nextLine();
        System.out.println("客流相机IP：" + cameraIp + "，端口：" + 8004+"开始建立连接");
        scanner.close();
        doDe(cameraIp,8004);
    }

    static void doDe(String cameraIp, int port) {
        //1.启动WebSocket服务
        SocketServer socketServer = new SocketServer(new InetSocketAddress(8889));
        socketServer.start();
        //2.启动CameraClient服务
        new Thread(() -> {
            try {
                CameraClient cameraClient = new CameraClient(socketServer);
                cameraClient.client(new InetSocketAddress(cameraIp, port));

            } catch (Exception e) {
                logger.log(Level.SEVERE, "Error: ", e);
            }
        }).start();

        //3.启动 ProtonServer服务
        new Thread(() -> {
            final int maxRetries = 5;
            final long retryInterval = 3000;
            int retryCount = 0;
            while (retryCount < maxRetries) {
                try {
                    // 创建服务器对象并启动服务器
                    ProtonServer protonServer = new ProtonServer(socketServer);
                    protonServer.server(portForProton);
                    // 服务器启动成功后，退出循环
                    break;
                } catch (IOException e) {
                    logger.log(Level.SEVERE, "Error: ", e);
                    if (e.getMessage().contains("The remote host forcibly closed an existing connection")) {
                        retryCount++;
                        logger.log(Level.INFO, "Attempting to restart the server. Retry count: " + retryCount);
                        try {
                            Thread.sleep(retryInterval);
                        } catch (InterruptedException ex) {
                            Thread.currentThread().interrupt();
                            throw new RuntimeException("Thread was interrupted during retry delay.", ex);
                        }
                    } else {
                        throw new RuntimeException("An unexpected error occurred.", e);
                    }
                } catch (Exception e) {
                    logger.log(Level.SEVERE, "An unexpected error occurred: ", e);
                }
                if (retryCount >= maxRetries) {
                    logger.log(Level.SEVERE, "Failed to restart the server after " + maxRetries + " attempts.");
                }
            }
        }).start();
    }

    public static String getLocalIp() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = allNetInterfaces.nextElement();
                if (netInterface.isLoopback() || netInterface.isVirtual() ||!netInterface.isUp()) {
                    continue;
                }
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = addresses.nextElement();
                    if (ip instanceof java.net.Inet4Address) {
                        return ip.getHostAddress();
                    }
                }
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return "无法获取本机 IP，请自行查询";
    }
}
